import { createRouter, createWebHashHistory } from 'vue-router';

// 布局组件
const MainLayout = () => import('../layouts/MainLayout.vue');
const AuthLayout = () => import('../layouts/AuthLayout.vue');

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/auth/login'  // 默认重定向到登录页
  },
  {
    path: '/main',
    component: MainLayout,
    redirect: '/main/dashboard',
    meta: { requiresAuth: true },
    children: [
      // 公共页面
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/common/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'dashboard', roles: ['farmer', 'buyer', 'seller'] }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/common/Profile.vue'),
        meta: { title: '个人中心', icon: 'user', roles: ['farmer', 'buyer', 'seller'] }
      },
      {
        path: 'messages',
        name: 'Messages',
        component: () => import('../views/common/Messages.vue'),
        meta: { title: '消息中心', icon: 'message', roles: ['farmer', 'buyer', 'seller'] }
      },
      
      // 农户页面
      {
        path: 'farmer',
        name: 'FarmerRoot',
        redirect: '/main/farmer/land',
        meta: { roles: ['farmer'] },
        children: [
          {
            path: 'land',
            name: 'LandManagement',
            component: () => import('../views/farmer/LandManagement.vue'),
            meta: { title: '土地管理', icon: 'map', roles: ['farmer'] }
          },
          {
            path: 'planting',
            name: 'PlantingManagement',
            component: () => import('../views/farmer/PlantingManagement.vue'),
            meta: { title: '种植管理', icon: 'plant', roles: ['farmer'] }
          },
          {
            path: 'fertilizer',
            name: 'FertilizerManagement',
            component: () => import('../views/farmer/FertilizerManagement.vue'),
            meta: { title: '施肥管理', icon: 'fertilizer', roles: ['farmer'] }
          },
          {
            path: 'inventory',
            name: 'InventoryManagement',
            component: () => import('../views/farmer/InventoryManagement.vue'),
            meta: { title: '库存管理', icon: 'inventory', roles: ['farmer'] }
          },
          {
            path: 'trade',
            name: 'FarmerTrade',
            component: () => import('../views/farmer/FarmerTrade.vue'),
            meta: { title: '交易中心', icon: 'trade', roles: ['farmer'] }
          }
        ]
      },
      
      // 农产品买家页面
      {
        path: 'buyer',
        name: 'BuyerRoot',
        redirect: '/main/buyer/orders',
        meta: { roles: ['buyer'] },
        children: [
          {
            path: 'orders',
            name: 'OrderManagement',
            component: () => import('../views/buyer/OrderManagement.vue'),
            meta: { title: '订单管理', icon: 'order', roles: ['buyer'] }
          },
          {
            path: 'farmers',
            name: 'FarmerList',
            component: () => import('../views/buyer/FarmerList.vue'),
            meta: { title: '农户浏览', icon: 'farmer', roles: ['buyer'] }
          },
          {
            path: 'complaints',
            name: 'ComplaintManagement',
            component: () => import('../views/buyer/ComplaintManagement.vue'),
            meta: { title: '投诉管理', icon: 'complaint', roles: ['buyer'] }
          }
        ]
      },
      
      // 肥料卖家页面
      {
        path: 'seller',
        name: 'SellerRoot',
        redirect: '/main/seller/products',
        meta: { roles: ['seller'] },
        children: [
          {
            path: 'products',
            name: 'ProductManagement',
            component: () => import('../views/seller/ProductManagement.vue'),
            meta: { title: '商品管理', icon: 'product', roles: ['seller'] }
          },
          {
            path: 'seller-orders',
            name: 'SellerOrderManagement',
            component: () => import('../views/seller/SellerOrderManagement.vue'),
            meta: { title: '订单处理', icon: 'order-process', roles: ['seller'] }
          }
        ]
      }
    ]
  },
  
  // 认证相关路由
  {
    path: '/auth',
    component: AuthLayout,
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('../views/auth/Login.vue'),
        meta: { title: '登录' }
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('../views/auth/Register.vue'),
        meta: { title: '注册' }
      }
    ]
  },
  
  // 错误页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/error/NotFound.vue')
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token和用户角色
  const token = localStorage.getItem('token');
  const userRole = localStorage.getItem('userRole');
  console.log('路由守卫检查 - 目标路径:', to.path, '- Token:', !!token, '- 角色:', userRole);

  // 如果是登录或注册页面
  if (to.path === '/auth/login' || to.path === '/auth/register') {
    // 如果已登录，跳转到主页（但如果是从主页来的，不再跳转，防止循环）
    if (token && from.path !== '/main/dashboard') {
      console.log('已登录，从登录页跳转到主页');
      next('/main/dashboard');
    } else {
      console.log('进入登录/注册页');
      next();
    }
    return;
  }

  // 如果是需要认证的页面
  if (to.matched.some(record => record.meta.requiresAuth)) {
    console.log('访问需要认证的页面');
    
    // 如果未登录，跳转到登录页
    if (!token) {
      console.log('未登录，跳转到登录页');
      next('/auth/login');
      return;
    }

    // 如果路径是/main，直接重定向到dashboard
    if (to.path === '/main') {
      console.log('主路径重定向到仪表盘');
      next('/main/dashboard');
      return;
    }

    // 如果需要特定角色
    if (to.meta.roles && to.meta.roles.length > 0 && !to.meta.roles.includes(userRole)) {
      console.log('角色不匹配，重定向到仪表盘');
      
      // 基于角色重定向到相应的页面
      if (userRole === 'farmer') {
        next('/main/farmer/land');
      } else if (userRole === 'buyer') {
        next('/main/buyer/orders');
      } else if (userRole === 'seller') {
        next('/main/seller/products');
      } else {
        next('/main/dashboard');
      }
      return;
    }
  }

  // 默认放行
  console.log('默认放行到:', to.path);
  next();
});

export default router;
